package com.yang.utils;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;


@Component
public class FileDfsUtil {

    @Resource
    private FastFileStorageClient storageClient ;

    /**
     * 上传文件
     */
    public String upload(MultipartFile multipartFile) throws Exception{
        String originalFilename = multipartFile.getOriginalFilename().
                substring(multipartFile.getOriginalFilename().
                        lastIndexOf(".") + 1);
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                multipartFile.getInputStream(),
                multipartFile.getSize(),originalFilename , null);
        return storePath.getFullPath() ;
    }

    /**
     * 删除文件
     */
    public void deleteFile(String fileUrl) {
        JsonResult jsonResult = new JsonResult();
        if (StringUtils.isEmpty(fileUrl)) {
            System.out.println("fileUrl == >>文件路径为空...");
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 下载文件
     */
    public void download(String path, HttpServletResponse response) throws IOException {
        StorePath storePath = StorePath.praseFromUrl(path);
        String filename = URLEncoder.encode(path.substring(path.lastIndexOf("/")), "utf-8"); // 解决中文文件名下载后乱码的问题
        // 告诉浏览器 下载的文件名
        response.setHeader("Content-Disposition", "attachment; filename=" + filename + "");
        // 将文件的内容输出到浏览器 fastdfs
        byte[] downloadFile = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(),new DownloadByteArray());
        response.getOutputStream().write(downloadFile);
    }
}